import json
from pyoauth2 import Client

KEY = '101235071'
SECRET = '3f69998949d80e5052bf48a434f08cd3'
CALLBACK = 'http://xgz.xkk.pw/social/bind/qq'
OPENID_URL = 'https://graph.qq.com/oauth2.0/me'
USERINFO_URL = 'https://graph.qq.com/user/get_user_info'


def json_to_dict(x):
    '''OAuthResponse class can't not parse the JSON data with content-type
    text/html, so we need reload the JSON data manually'''
    if x.find('callback') > -1:
        pos_lb = x.find('{')
        pos_rb = x.find('}')
        x = x[pos_lb:pos_rb + 1]
    try:
        return json.loads(x, encoding='utf-8')
    except:
        return x


client = Client(KEY, SECRET,
                site='https://graph.qq.com',
                authorize_url='https://graph.qq.com/oauth2.0/authorize',
                token_url='https://graph.qq.com/oauth2.0/token',
)

authorize_url = client.auth_code.authorize_url(redirect_uri=CALLBACK,
                    scope='get_user_info,list_album,upload_pic,do_like')


def get_token(code):
    code = code.strip()
    access_token = client.auth_code.get_token(code, redirect_uri=CALLBACK, parse='query')
    return access_token


def get_openid(token):
    # response = client.request('GET', OPENID_URL, params={'access_token':token})
    response = client.request('GET', OPENID_URL, access_token=token)
    dict = json_to_dict(response.body)
    return dict.get('openid')


def get_user_info(token, openid):
    response = client.request('GET', USERINFO_URL, access_token=token, oauth_consumer_key=KEY, openid=openid)
    return response.body
